import datetime
import json
import os.path
import re


def step_read():
    if os.path.isfile('cache/zw_report.json'):
        with open('cache/zw_report.json', 'r', encoding='utf-8') as f:
            content = f.read()
            if content:
                return json.loads(content)
    return []


def step_update(content):
    if not os.path.exists('cache'):
        os.mkdir('cache')
    with open('cache/zw_report.json', 'w+', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False))


template = """【割接通报】
割接主题：{title}
工单号：{number}
割接开始时间：{time_1}
操作结束时间：待定
业务验证完成时间：待定
割接完成时间：待定
割接结果：待定
"""


def main():
    histories = step_read()
    if histories and len(histories) != 5:
        if len(histories) == 4:
            result = histories[-1].replace('待定', '割接成功，业务验证正常', 1)
        else:
            now_time = datetime.datetime.now().strftime('%Y年%m月%d日%H:%M')
            result = histories[-1].replace('待定', now_time, 1)
        histories.append(result)
        step_update(histories)
        _console(result)

    else:
        title = re.findall(r'发起(.*)', text)[0]
        number = re.findall(r'工单号：(\d+)', text)[0]
        time_1 = datetime.datetime.now().strftime('%Y年%m月%d日23:00')
        result = template.format(title=title.strip(), number=number, time_1=time_1)
        step_update([result, ])
        _console(result)

    remind = f"""
1.割接过程通报
2.更新云鸽割接管理看板
3.关闭割接工单（云鸽/运维工作台）
4.更新相关在线表：
->①https://docs.qq.com/sheet/DZk9DV0V4S0JhQ0tV?tab=bgzwbf
->②https://docs.qq.com/sheet/DQ2VWVHJJY2tMdm1S?u=d0fb53a8521e40e9b7f8894126facb9f&tab=BB08J2
5.发送割接情况总结邮件
        """
    _console("割接注意事项:", remind.rstrip())